package com.green.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import com.green.common.util.PBEUtils;
import com.green.common.util.StringUtil;

/**
 * 字段加密/解密
 * 
 * @author Hou Peiqin
 *
 */
public class FieldCoder {
	
	private static final String SUFFIX = "=\r\n";
	
	private static final String REGEX = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
	
	private static final String NEW_LINE = "\r\n";
	
	private static final String EMPTY= "";
	
	//for test
	private static String password = "123456";
	private static String salt = "abcdefgh";
	public static String encode(String value) {
		if(StringUtils.isEmpty(value)){
			return value;
		}
        byte[] data = PBEUtils.encrypt(value.getBytes(), password, salt.getBytes());  
        return PBEUtils.encryptBASE64(data);
	}
	
	public static String decode(String value) {
		if(StringUtils.isEmpty(value)){
			return value;
		}
		byte[] data = PBEUtils.decryptBASE64(value);
        byte[] output = PBEUtils.decrypt(data, password, salt.getBytes());  
        return new String(output);  
	}
	
	public static boolean isEncodedValue(String value) {
		if(StringUtils.isNotEmpty(value)){
			if(value.endsWith(SUFFIX)){
				return true;
			}else{
				if(value.endsWith(NEW_LINE)){
					value = value.replace(NEW_LINE, EMPTY);
					if(StringUtil.isDouble(value) || StringUtil.isInteger(value)){
						return false;
					}else{
						Pattern pattern = Pattern.compile(REGEX);
						Matcher matcher = pattern.matcher(value);
						return matcher.matches();
					}
				}
			}
		}
		return false;
	}
	
}
